require 'mina/bundler'
require 'mina/rails'
require 'mina/git'
require 'mina/rvm'
require 'mina/whenever'

environments = {
  'develop' => {
    domain: 'cloudchain.com.cn',
    branch: 'develop'
  },
  'staging' => {
    domain: 'cloudchain.co',
    branch: 'staging'
  },
  'production' => {
    domain: 'cloudchain.cn',
    branch: 'master'
  }
}

rails_env = environments.keys.include?(ENV['RAILS_ENV']) ? ENV['RAILS_ENV'] : 'develop'
branch = environments[rails_env][:branch]
domain = environments[rails_env][:domain]

set :rails_env, rails_env
set :domain, domain
set :deploy_to, "/var/app/#{domain}"
set :repository, 'git@github.com:china-east-soft/YmtvWeb.git'
set :branch, branch
set :ssh_options, '-A'

set :shared_paths, ['log', '.private_key', 'tmp/restart.txt', "config/#{domain}", 'public/uploads', 'public/robots.txt']

set :user, 'root'
set :term_mode, :nil

set :rvm_path, '/usr/local/rvm/scripts/rvm'

task :environment do
  invoke :'rvm:use[ruby-1.9.3-p448@default]'
end

task :setup => :environment do
  queue! %[mkdir -p "#{deploy_to}/shared/log"]
  queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/log"]

  queue! %[mkdir -p "#{deploy_to}/shared/tmp"]
  queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/tmp"]

  queue! %[touch "#{deploy_to}/shared/tmp/restart.txt"]
  queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/tmp/restart.txt"]

  queue! %[mkdir -p "#{deploy_to}/shared/config"]
  queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/config"]

  queue! %[touch "#{deploy_to}/shared/config/#{domain}"]
  queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/config/#{domain}"]

  queue! %[mkdir -p "#{deploy_to}/shared/public"]
  queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/public"]

  queue! %[touch "#{deploy_to}/shared/public/uploads"]
  queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/public/uploads"]

  queue! %[touch "#{deploy_to}/shared/public/robots.txt"]
  queue! %[chmod g+rx,u+rwx "#{deploy_to}/shared/public/robots.txt"]
  
  invoke :nginx
end

desc "Deploys the current version to the server."
task :deploy => :environment do
  deploy do
    invoke :'git:clone'
    invoke :'deploy:link_shared_paths'
    invoke :'bundle:install'
    invoke :'rails:db_migrate'
    invoke :'rails:assets_precompile'

    to :launch do
      invoke :'whenever:update'
      queue "touch #{deploy_to}/#{current_path}/tmp/restart.txt"
      invoke :'deploy:cleanup'
    end
  end
end

desc "Generate Nginx conf and write it"
task :nginx => :environment do
  nginx_conf = erb("config/nginx.erb")
  queue %[echo "#{nginx_conf}" > "#{deploy_to}/shared/config/#{domain}"]
  queue "ln -fs #{deploy_to}/shared/config/#{domain} /opt/nginx/conf/sites/#{domain}"
end
